import { View, Text, Image } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { 
  Card, 
  Button, 
  Tag,
  Tabs,
  TabPane,
  Empty
} from '@nutui/nutui-react-taro'
import Taro, { useLoad, useDidShow } from '@tarojs/taro'
import { orderApi, userApi } from '../../api/index'
import './index.less'

export default function Orders() {
  const [userInfo, setUserInfo] = useState(null)
  const [orders, setOrders] = useState([])
  const [loading, setLoading] = useState(false)
  const [activeTab, setActiveTab] = useState('0')

  // 订单状态映射
  const statusMap = {
    1: { text: '进行中', color: '#ff8f1f', bgColor: '#fff7e6' },
    2: { text: '已完成', color: '#52c41a', bgColor: '#f6ffed' },
    3: { text: '待付款', color: '#1890ff', bgColor: '#e6f7ff' },
    4: { text: '已取消', color: '#999', bgColor: '#f5f5f5' }
  }

  // Tab 配置
  const tabs = [
    { title: '全部', value: '0' },
    { title: '进行中', value: '1' },
    { title: '已完成', value: '2' },
    { title: '待付款', value: '3' }
  ]

  useLoad(() => {
    checkLogin()
  })

  useDidShow(() => {
    checkLogin()
    loadOrders()
  })

  const checkLogin = async () => {
    try {
      // 尝试多个可能的存储 key
      let user = Taro.getStorageSync('userInfo') || 
                 Taro.getStorageSync('user') || 
                 Taro.getStorageSync('loginUser')
      
      // 如果没有用户信息，创建一个模拟用户（开发阶段）
      if (!user) {
        user = {
          id: 1,
          phone: '138****8888',
          name: '用户',
          avatar: 'https://img.yzcdn.cn/vant/cat.jpeg'
        }
        // 存储用户信息
        Taro.setStorageSync('userInfo', user)
        console.log('创建模拟用户信息')
      }
      
      setUserInfo(user)
    } catch (error) {
      console.log('获取用户信息失败:', error)
      // 开发阶段不跳转登录页，直接创建模拟用户
      const mockUser = {
        id: 1,
        phone: '138****8888',
        name: '用户',
        avatar: 'https://img.yzcdn.cn/vant/cat.jpeg'
      }
      setUserInfo(mockUser)
      Taro.setStorageSync('userInfo', mockUser)
    }
  }

  const loadOrders = async () => {
    try {
      setLoading(true)
      const orderData = await orderApi.getOrderList()
      
      // 模拟订单数据，符合设计图
      const mockOrders = [
        {
          id: 1,
          orderNo: 'YX20230512001',
          status: 1,
          statusText: '进行中',
          serviceType: '鞋子洗护 + 衣物清洗',
          serviceDetail: '2双运动鞋 + 3件上衣',
          amount: 89.00,
          createTime: '今天 10:30',
          image: 'https://img.yzcdn.cn/vant/cat.jpeg',
          orderCode: '123456'
        },
        {
          id: 2,
          orderNo: 'YX20230511002',
          status: 2,
          statusText: '已完成',
          serviceType: '干洗服务',
          serviceDetail: '1件羽绒服 + 1条羊毛围巾',
          amount: 120.00,
          createTime: '昨天 15:00',
          image: 'https://img.yzcdn.cn/vant/cat.jpeg',
          orderCode: null
        },
        {
          id: 3,
          orderNo: 'YX20230511003',
          status: 3,
          statusText: '待付款',
          serviceType: '衣物清洗',
          serviceDetail: '5件打底',
          amount: 50.00,
          createTime: '前天 09:00',
          image: 'https://img.yzcdn.cn/vant/cat.jpeg',
          orderCode: null
        }
      ]
      
      setOrders(mockOrders)
    } catch (error) {
      console.log('获取订单列表失败:', error)
      setOrders([])
    } finally {
      setLoading(false)
    }
  }

  const getFilteredOrders = () => {
    if (activeTab === '0') return orders
    return orders.filter(order => order.status.toString() === activeTab)
  }

  const handleOrderClick = (order) => {
    Taro.navigateTo({
      url: `/pages/order-detail/index?orderId=${order.id}`
    })
  }

  const handleAction = (order, action) => {
    switch (action) {
      case 'pay':
        Taro.navigateTo({
          url: `/pages/payment/index?orderId=${order.id}&amount=${order.amount}`
        })
        break
      case 'cancel':
        Taro.showModal({
          title: '确认取消',
          content: '确定要取消这个订单吗？',
          success: (res) => {
            if (res.confirm) {
              handleCancelOrder(order.id)
            }
          }
        })
        break
      case 'evaluate':
        Taro.showToast({
          title: '评价功能开发中',
          icon: 'none'
        })
        break
      case 'contact':
        Taro.showModal({
          title: '联系客服',
          content: '客服电话：400-888-8888\n工作时间：7×24小时',
          showCancel: false,
          confirmText: '知道了'
        })
        break
      default:
        break
    }
  }

  const handleCancelOrder = async (orderId) => {
    try {
      await orderApi.cancelOrder(orderId)
      Taro.showToast({
        title: '订单已取消',
        icon: 'success'
      })
      loadOrders()
    } catch (error) {
      Taro.showToast({
        title: '取消失败',
        icon: 'error'
      })
    }
  }

  const getActionButtons = (order) => {
    switch (order.status) {
      case 1: // 进行中
        return [
          <Button 
            key="contact" 
            size="small" 
            type="default"
            className="action-btn secondary"
            onClick={() => handleAction(order, 'contact')}
          >
            联系客服
          </Button>,
          <Button 
            key="cancel" 
            size="small" 
            type="default"
            className="action-btn secondary"
            onClick={() => handleAction(order, 'cancel')}
          >
            取消订单
          </Button>
        ]
      case 2: // 已完成
        return [
          <Button 
            key="evaluate" 
            size="small" 
            type="primary"
            className="action-btn primary"
            onClick={() => handleAction(order, 'evaluate')}
          >
            去评价
          </Button>
        ]
      case 3: // 待付款
        return [
          <Button 
            key="pay" 
            size="small" 
            type="primary"
            className="action-btn primary"
            onClick={() => handleAction(order, 'pay')}
          >
            待付款
          </Button>
        ]
      default:
        return []
    }
  }

  if (!userInfo) {
    return null
  }

  return (
    <View className='orders-page'>
      {/* 顶部 Tabs */}
      <View className='tabs-container'>
        <Tabs 
          value={activeTab} 
          onChange={setActiveTab}
          className='order-tabs'
        >
          {tabs.map(tab => (
            <TabPane key={tab.value} title={tab.title} paneKey={tab.value} />
          ))}
        </Tabs>
      </View>

      {/* 订单列表 */}
      <View className='orders-list'>
        {loading ? (
          <View className='loading'>
            <Text>加载中...</Text>
          </View>
        ) : getFilteredOrders().length > 0 ? (
          getFilteredOrders().map(order => (
            <Card key={order.id} className='order-card'>
              {/* 订单头部 */}
              <View className='order-header'>
                <View className='order-info'>
                  <Tag 
                    color={statusMap[order.status]?.color}
                    textColor='white'
                    size='small'
                    className='status-tag'
                  >
                    {statusMap[order.status]?.text}
                  </Tag>
                  <Text className='order-no'>订单编号：{order.orderNo}</Text>
                </View>
                <Text className='order-time'>{order.createTime}</Text>
              </View>

              {/* 订单内容 */}
              <View className='order-content' onClick={() => handleOrderClick(order)}>
                <Image 
                  src={order.image} 
                  className='service-image'
                  mode='aspectFill'
                />
                <View className='service-info'>
                  <Text className='service-type'>{order.serviceType}</Text>
                  <Text className='service-detail'>{order.serviceDetail}</Text>
                  <Text className='service-price'>¥{order.amount.toFixed(2)}</Text>
                </View>
              </View>

              {/* 取件码 */}
              {order.orderCode && (
                <View className='pickup-code'>
                  <Text className='code-label'>取件码：</Text>
                  <Text className='code-number'>{order.orderCode}</Text>
                </View>
              )}

              {/* 操作按钮 */}
              <View className='order-actions'>
                {getActionButtons(order)}
              </View>
            </Card>
          ))
        ) : (
          <Empty 
            description="暂无订单"
            imageSize={200}
            className='empty-state'
          />
        )}
      </View>
    </View>
  )
}